<template>
	<view class="tabs-container">
		<!-- 自定义 Tab 标签 -->
		<view class="tab-header">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: activeIndex === index }"
				@click="switchTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 滑动区域 -->
		<swiper class="swiper-container" :current="activeIndex" @change="handleSwiperChange" :duration="300">
			<swiper-item v-for="(tab, index) in tabs" :key="index">
				<scroll-view scroll-y="true" class="swiper-scroll">
					<transition name="fade" mode="out-in">
						<view v-show="activeIndex === index" class="swiper-content">
							<keep-alive>
								<CarTab v-if="index === 0 && shouldRender(index)" />
								<MealTab v-if="index === 1 && shouldRender(index)" />
								<ItemTab v-if="index === 2 && shouldRender(index)" />
							</keep-alive>
						</view>
					</transition>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import CarTab from './car.vue'
	import MealTab from './meal.vue'
	import ItemTab from './item.vue'

	export default {
		components: {
			CarTab,
			MealTab,
			ItemTab
		},
		data() {
			return {
				tabs: ['出行', '用餐', '物品'],
				activeIndex: 0,
				loadedPages: [false, false, false]
			}
		},
		mounted() {
			this.activeIndex = uni.$router.params.activeIndex || 0
			console.log(uni.$router.params.activeIndex,'activeIndex')
			this.preloadData(this.activeIndex)
		},
		methods: {
			switchTab(index) {
				if (this.activeIndex !== index) {
					this.activeIndex = index
					this.preloadData(index)
				}
			},
			handleSwiperChange(e) {
				const index = e.detail.current
				if (this.activeIndex !== index) {
					this.activeIndex = index
					this.preloadData(index)
				}
			},
			preloadData(index) {
				if (!this.loadedPages[index]) {
					this.loadedPages[index] = true
				}
			},
			shouldRender(index) {
				return this.loadedPages[index] || index === this.activeIndex
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tabs-container {
		padding: 20rpx;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}

	.tab-header {
		display: flex;
		justify-content: center;
		margin-bottom: 1rpx;
		background-color: #f0f0f0;
		border-radius: 80rpx;
		width: 60%;
		margin-left: 20%;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		color: #666;
		overflow: hidden;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		z-index: 1;
		position: relative;
		transition: all 0.3s ease;
	}

	.tab-item.active {
		background-color: #007AFF;
		color: #fff;
	}

	.swiper-container {
		flex: 1;
		height: calc(100vh - 150rpx);
		overflow-y: auto;
	}

	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.3s ease;
	}

	.fade-enter-from,
	.fade-leave-to {
		opacity: 0;
	}

	.swiper-scroll {
		height: 100%;
	}
</style>